Java Class and Objects

Java is an object-oriented programming language. So everything in java is associated with classes & objects.

In a class everything is break down into small objects.

Java Class

A class in java is a collection of objects. It is the blueprint of the object. A class can contain variables and methods to determin the state and the behavior of the object.

The variables are used to store the data and the methods are used to perform some task.

Syntax

Class className
{
   // variables
   // methods
}

Example

class Car{

  // variable
  private int gear = 5;

  // method
  public void accelerate() {
    System.out.println("Working of Accelerate");
  }
}

Here, the class Car has a variable gear to hold the state of the car. The accelerate is the method to perform the task of an accelerator of a car.

Java Object

In java, object is the instance of a class. The instance of a class will have the access to the variables and methods of the class based on the access specifiers.

Syntax

className objectName = new className();

Example

Car sportsCar = new Car();
Car luxuryCar = new Car();

Example Program

class Car{

  // variable
  public int gear = 5;

  // method
  public void accelerate() {
    System.out.println("Working of Accelerate");
  }
}

class Main {
    public static void main(String args[]){
        Car myCar = new Car();
        System.out.println(myCar.gear);
        myCar.accelerate();
    }
}

Output

5
Working of Accelerate

In the above example, the class named Car has a property gear and a method accelerate.


Most Read